package online.longzipeng.back.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import online.longzipeng.back.common.exception.MessageException;
import online.longzipeng.back.mapper.UserMapper;
import online.longzipeng.back.pojo.entity.User;
import online.longzipeng.back.pojo.vo.UserInfoVo;
import online.longzipeng.back.pojo.vo.UserVo;
import online.longzipeng.back.service.UserService;
import online.longzipeng.back.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author lzp
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Value("${config.wechat.appId}")
    private String appId;
    @Value("${config.wechat.appSecret}")
    private String appSecret;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public UserInfoVo login(UserInfoVo userInfo) {
        StringBuilder url = new StringBuilder("https://api.weixin.qq.com/sns/jscode2session?appid=")
                .append(appId).append("&secret=").append(appSecret)
                .append("&js_code=").append(userInfo.getCode()).append("&grant_type=authorization_code");
        String json = HttpUtil.get(url.toString());
        JSONObject loginResult = JSONObject.parseObject(json);
        // 取出openId和sessionKey
        Object session_key = loginResult.get("session_key");
        Object openid = loginResult.get("openid");
        Object errmsg = loginResult.get("errmsg");
        if (ObjectUtil.isNull(session_key) || ObjectUtil.isNull(openid)) {
            throw new MessageException("登录失败，请重试！！");
        }
        if (ObjectUtil.isNotNull(errmsg)) {
            throw new MessageException(errmsg.toString());
        }
        // 通过penId查找用户，判断是否已登录过
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getWechatId, openid.toString()));
        // 新用户
        if (ObjectUtil.isNull(user)) {
            user = new User();
            BeanUtil.copyProperties(userInfo, user);
            user.setWechatId(openid.toString());
            userMapper.insert(user);
            UserUtils.setToken(userInfo, user);
            return userInfo;
        } else {
            // 老用户
            BeanUtil.copyProperties(user, userInfo);
            UserUtils.setToken(userInfo, user);
            return userInfo;
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public UserInfoVo saveUserInfo(UserInfoVo userInfo) {
        if (ObjectUtil.isNotNull(userInfo.getId())) {
            User user = new User();
            BeanUtil.copyProperties(userInfo, user);
            userMapper.updateById(user);
            // 更新成功，重新存一次token
            UserUtils.setToken(userInfo, user);
        }
        return userInfo;
    }

    @Override
    public List<UserVo> search(String nickName,Long teamId) {
        return userMapper.search(nickName,teamId,UserUtils.getUserId());
    }
}
